#include"mystdio.h"

myFILE* my_fopen(const char* path,const char* mode){
    int fd = -1;
    switch(strlen(mode))
    {
            case 1:
              switch(mode[0])
              {
                    case 'w':
                        fd = open(path,O_WRONLY | O_CREAT | O_TRUNC,0666);
                        break;
                    case 'r':
                        fd = open(path,O_RDONLY);
                        break;
                    case 'a':
                        fd = open(path,O_WRONLY | O_APPEND | O_CREAT,0666);
                        break;
              }
              break;
            case 2:
              switch(mode[0])
              {
                    case 'w':
                        fd = open(path,O_RDWR | O_CREAT);
                        break;
                    case 'r':
                        fd = open(path,O_RDWR | O_CREAT,0666);
                        break;
                    case 'a':
                        fd = open(path,O_WRONLY | O_APPEND | O_CREAT ,0666);
              }
              break;
        
    }
    
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL){
          perror("malloc failed\n");
    }
    fp->fileno = fd;
    return fp;
        
}


ssize_t my_fwrite(myFILE* fp,const char* data,int len){
    int count = 0;
    while(1){
        if(strlen(data) - count > LINE_SIZE - fp->pos){
            strncpy(fp->cache + fp->pos,data + count,LINE_SIZE -fp-> pos);
            count += LINE_SIZE - fp->pos;
            fp->pos = 0;
            fp->cap = LINE_SIZE;
        }
        else{ 
            strcpy(fp->cache + fp->pos,data + count);
            fp->pos += strlen(data) - count; 
            fp->cache[fp->pos] = '\0';
            break;
        }
    }
    if(data[len - 1] == '\n'){
        my_fflush(fp);
    }
    return len;
}
void my_fflush(myFILE*fp){ 
    write(fp->fileno,fp->cache,fp->pos);
    fp->pos = 0;
}
void my_fclose(myFILE*fp){
    my_fflush(fp);
    close(fp->fileno);
}

